package com.changcheng.project.yuminsi.service.impl;


import com.changcheng.project.yuminsi.commons.RestTemplateCommons;
import com.changcheng.project.yuminsi.mapper.CommonMapper;
import com.changcheng.project.yuminsi.domain.CarDomain;
import com.changcheng.project.yuminsi.error.BusinessException;
import com.changcheng.project.yuminsi.error.GlobalErrorCode;
import com.changcheng.project.yuminsi.service.TempService;
import com.changcheng.project.yuminsi.utils.GenerateSignUtil;
import com.changcheng.project.yuminsi.vo.BaseOutput;
import com.changcheng.project.yuminsi.vo.CcCodeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuminsi
 * @description
 * @date 2020/9/16 14:41
 * @since
 */
@SuppressWarnings("all")
@Service
public class TempServiceImpl implements TempService {

    private static final Logger logger = LoggerFactory.getLogger(TempServiceImpl.class);
    
    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private RestTemplateCommons restTemplate;

    @Autowired
    private HttpServletRequest request;

    private static String appkey = "9065275281";
    private static String secretkey = "2b673290caa2d9a82f1f7e845c80e4fe";


    /**
     * IC卡复合消费消费计算Mac
     *
     * 国密IC卡消费计算MAC:密钥体系（0聚利，1速通）+4字节区域代码+8字节卡内部编号+4字节伪随机数+2字节脱机交易序号
     * +1字节密钥版本号+1字节算法标识+4字节消费金额+6字节终端机编号+4字节终端交易序号+7字节交易时间+返回IC卡COS指令
     *
     * @param strAreaCodeNumber
     * @param strIcSerialNumber
     * @param strRand
     * @param strIccTradeSerialNum
     * @param strKeyVer
     * @param strAlgId
     * @param strConsumeNumber
     * @param strTerminalNum
     * @param strPsamTradeNum
     * @param strDateTime
     * @return
     */
    @Override
    public BaseOutput consumeCalMac(String strAreaCodeNumber, String strIcSerialNumber, String strRand, String strIccTradeSerialNum, String strKeyVer, String strAlgId, String strConsumeNumber, String strTerminalNum, String strPsamTradeNum, String strDateTime) {
        //密钥体系（0聚利，1速通）
        Integer keySystemType = 0;

        StringBuilder sb = new StringBuilder();
        sb.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n");
        sb.append("<soap12:Body>\n");
        sb.append("<GM_ICC_CONSUME_CALMAC_ALL xmlns=\"http://tempuri.org/\">\n");
        sb.append("<nKeySystemType>" + keySystemType + "</nKeySystemType>\n");
        sb.append("<strAreaCodeNumber>" + strAreaCodeNumber + "</strAreaCodeNumber>\n");
        sb.append("<strIcSerialNumber>" + strIcSerialNumber + "</strIcSerialNumber>\n");
        sb.append("<strRand>" + strRand + "</strRand>\n");
        sb.append("<strIccTradeSerialNum>" + strIccTradeSerialNum + "</strIccTradeSerialNum>\n");
        sb.append("<strKeyVer>" + strKeyVer + "</strKeyVer>\n");
        sb.append("<strAlgId>" + strAlgId + "</strAlgId>\n");
        sb.append("<strConsumeNumber>" + strConsumeNumber + "</strConsumeNumber>\n");
        sb.append("<strTerminalNum>" + strTerminalNum + "</strTerminalNum>\n");
        sb.append("<strPsamTradeNum>" + strPsamTradeNum + "</strPsamTradeNum>\n");
        sb.append("<strDateTime>" + strDateTime + "</strDateTime>\n");
        sb.append("<RCos>" + "" + "</RCos>\n");
        sb.append("</GM_ICC_CONSUME_CALMAC_ALL>\n");
        sb.append("</soap12:Body>\n");
        sb.append("</soap12:Envelope>\n");

        //获取cos指令
        String cos = restTemplate.getRcos(sb);

        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, cos);
    }

    /**
     * 解密车辆信息
     *
     * 国密ESAM解密车辆密文:密钥体系（0聚利，1速通）+4字节区域代码+8字节OBU合同序列号+8字节随机数+N字节车辆信息密文
     *  +1字节加密密钥版本+返回车辆信息明文
     *
     * @param strAreaCodeNumber
     * @param strEsamSerialNumber
     * @param strRand
     * @param strEnCryptData
     * @param strKeyVer
     * @return
     */
    @Override
    public BaseOutput decryptVehi(String strAreaCodeNumber, String strEsamSerialNumber, String strRand, String strEnCryptData, String strKeyVer) {

        //密钥体系（0聚利，1速通）
        Integer keySystem = 0;

        StringBuilder sb = new StringBuilder();
        sb.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
        sb.append("<soap12:Body>");
        sb.append("<GM_ESAM_DECRYPTVEHI_CALMAC_ALL xmlns=\"http://tempuri.org/\">");
        sb.append("<nKeySystemType>" + keySystem + "</nKeySystemType>");
        sb.append("<strAreaCodeNumber>" + strAreaCodeNumber + "</strAreaCodeNumber>");
        sb.append("<strEsamSerialNumber>" + strEsamSerialNumber + "</strEsamSerialNumber>");
        sb.append("<strRand>" + "FDE6FD128EA699F7" + "</strRand>");
        sb.append("<strEnCryptData>" + strEnCryptData + "</strEnCryptData>");
        sb.append("<strKeyVer>" + strKeyVer + "</strKeyVer>");
        sb.append("<RCos>" + "" + "</RCos>");
        sb.append("</GM_ESAM_DECRYPTVEHI_CALMAC_ALL>");
        sb.append("</soap12:Body>");
        sb.append("</soap12:Envelope>");

        logger.info("sb:{}", sb);
        logger.info("restTemplate:{}", restTemplate);

        //获取cos
        String cos = restTemplate.getRcos(sb);
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, cos);
    }


    /**
     * 通过VIN码获取车型编码/cc码
     * @param vin
     * @return
     */
    @Override
    public BaseOutput getVehiCcCode(String vin) throws Exception {
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();
        logger.info("路径:  {}", uri);

        //参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("", "");


        String genSign = GenerateSignUtil.generateSignOfGet(uri, appkey, nonce, timestamp, parameters, secretkey);
        logger.info("Get生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }

        CarDomain carDomain = commonMapper.queryCarInfoByVin(vin);
        if (carDomain == null){
            throw new BusinessException(GlobalErrorCode.FAIL);
        }
        String vehicleModelCode = carDomain.getVehicleModelCode();
        CcCodeResponse ccCodeResponse = new CcCodeResponse();
        ccCodeResponse.setVin(vin);
        ccCodeResponse.setVehicleModelCode(vehicleModelCode);
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, ccCodeResponse);
    }
}
